package priv.lhy.ecm.basic.aspect;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import priv.lhy.common.abs.AbstractRequest;
import priv.lhy.common.constants.AuthorPolicy;
import priv.lhy.ecm.basic.annotation.AuthorValidate;
import priv.lhy.ecm.basic.constants.BasicResponseCode;
import priv.lhy.ecm.basic.exception.BasicException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Method;

/**
 * @author: lihy
 * date: 2019/7/22 17:27
 * description:
 */
@Aspect
@Component
public class AuthorAspect {

    @Pointcut("@annotation(priv.lhy.ecm.basic.annotation.AuthorValidate)")
    public void authorPointcut() {
    }

    @Around("authorPointcut()")
    public Object Interceptor(ProceedingJoinPoint point) {
        MethodSignature signature = (MethodSignature) point.getSignature();
        Method method = signature.getMethod();
        Object[] args = point.getArgs();
        AbstractRequest request = null;
        for (Object arg : args) {
            if (arg instanceof AbstractRequest) {
                request = (AbstractRequest) arg;
                break;
            }
        }

        //获取注解中配置的权限
        AuthorPolicy[] authorPolicies = {AuthorPolicy.USER};
        Annotation[] annotations = method.getDeclaredAnnotations();
        for (Annotation ann : annotations) {
            if (ann.annotationType() == AuthorValidate.class) {
                authorPolicies = ((AuthorValidate) ann).value();
                break;
            }
        }

        //比较请求中携带的与注解中规定的权限
        for (AuthorPolicy ap : authorPolicies) {
            if (request.getAccessId().equals(ap)) {
                try {
                    //权限相同则执行方法
                    return point.proceed();
                } catch (Throwable throwable) {
                    throw new BasicException(BasicResponseCode.SYSTEM_BUSY.getCode(), BasicResponseCode
                            .SYSTEM_BUSY.getMsg(), request);
                }
            }
        }

        //未找到对应权限则抛异常
        throw new BasicException(BasicResponseCode.SYS_AUTHOR_ERROR.getCode(), BasicResponseCode
                .SYS_AUTHOR_ERROR.getMsg(), request);


    }
}
